package com.wannengbang.cloudleader.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;


public class GsonUlits {

    // 从一个json获取一个T对象并返回T,如一个用户的基本信息
    public static <T> T getObjectFromJson(String jsonString, Class<T> cls) {
        // import java.lang.reflect.Type;
        // import com.google.gson.reflect.TypeToken;
        T t = null;
        try {
            Gson gson = new Gson();
            t = gson.fromJson(jsonString, cls);
        } catch (Exception e) {
            // TODO: handle exception
        }
        return t;
    }

    // 从一个json获取一个List<T>对象并返回,如多个用户的基本信息
    public static <T> List<T> getObjectsFromJson(String jsonString, Class<T> cls) {
        List<T> list = new ArrayList<T>();
        try {
            Gson gson = new Gson();
            list = gson.fromJson(jsonString, new TypeToken<List<T>>() {
            }.getType());
        } catch (Exception e) {
            // TODO: handle exception
        }
        // TypeToken：反射机制

        return list;
    }

    public static Map<String, Object> getKeyapFromGson(String jsonString) {
        Map<String, Object> map = new HashMap<String, Object>();
        Gson gson = new Gson();
        try {
            map = gson.fromJson(jsonString,
                    new TypeToken<Map<String, Object>>() {
                    }.getType());
        } catch (Exception e) {
            // TODO: handle exception
        }

        return map;

    }

    // 相当与getObjectsFromJson的泛型T=String
    public static List<String> getListFromGson(String jsonString) {
        List<String> list = new ArrayList<String>();

        try {
            Gson gson = new Gson();
            list = gson.fromJson(jsonString, new TypeToken<List<String>>() {
            }.getType());
        } catch (Exception e) {
            // TODO: handle exception
        }

        return list;

    }

    public static List<Map<String, Object>> getListKeyapFromGson(
            String jsonString) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

        try {
            Gson gson = new Gson();
            list = gson.fromJson(jsonString,
                    new TypeToken<List<Map<String, Object>>>() {
                    }.getType());
        } catch (Exception e) {
            // TODO: handle exception
        }

        return list;

    }
}